<template>
  <div>
    <a-drawer
      :title="id ? '编辑配置项' : '新增配置项'"
      placement="right"
      :closable="false"
      :visible="visible"
      :maskClosable="false"
      :width="500"
      :destroyOnClose="true"
    >
      <a-form :form="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 12 }" style="padding-bottom: 30px;">
        <a-form-item label="配置名称" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-input
            :maxLength="20"
            placeholder="不得超过20个字"
            style="width: 210px;"
            v-decorator="['configurationName', { rules: [{ required: true, message: '配置名称不能为空' }] }]"
            :disabled="show"
          />
          <a-button type="link" icon="plus-circle" @click="add">添加状态</a-button>
        </a-form-item>
        <div v-for="(k, i) in form.getFieldValue('keys')" :key="i">
          <a-row class="status" type="flex" align="middle" justify="space-between">
            <a-col class="tit"> 状态{{ i + 1 }}： </a-col>
            <a-col v-if="i != 0">
              <a-button type="link" icon="delete" style="margin-left:14px;" @click="() => remove(k)">删除</a-button>
            </a-col>
          </a-row>
          <a-form-item label="配置状态">
            <a-input
              :maxLength="20"
              placeholder="不得超过20个字"
              style="width: 210px;"
              v-decorator="[
                `configurationStatus${i}`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: true,
                      whitespace: true,
                      message: '该项不能为空'
                    }
                  ]
                }
              ]"
            />
          </a-form-item>
          <a-form-item label="配置说明">
            <a-input :maxLength="20" placeholder="不得超过20个字" style="width: 210px;" v-decorator="[`configurationExplain${i}`]" />
          </a-form-item>
          <a-form-item label="工资影响">
            <a-input-number
              placeholder="请输入"
              style="width: 210px;"
              v-decorator="[
                `sallaryImpact${i}`,
                {
                  validateTrigger: ['change', 'blur'],
                  rules: [
                    {
                      required: true,
                      whitespace: true,
                      message: '该项不能为空'
                    }
                  ]
                }
              ]"
            />
          </a-form-item>
        </div>
      </a-form>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          取消
        </a-button>
        <a-button type="primary" @click="onAdd">
          确定
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { getASTIListAll, postBatchSave, putBatchUpdate } from "../../../api";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ""
    },
    attendanceSallaryTemplateId: {
      type: String,
      default: ""
    },
    name: {
      type: String,
      default: ""
    }
  },
  watch: {
    visible(v) {
      if (v) {
        this.show = false;
        if (this.id) {
          this.onGetASTIListAll();
        }
        if (this.name) {
          if (this.name === "考勤状态" || this.name === "工种") {
            this.show = true;
          }
        }
      }
    }
  },
  data() {
    return {
      deleteIds: [],
      show: false
    };
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, {});
    this.form.getFieldDecorator("keys", {
      initialValue: [{ configurationStatus: "", configurationExplain: "", sallaryImpact: "", id: null }],
      preserve: true
    });
  },
  methods: {
    async onGetASTIListAll() {
      try {
        const { data } = await getASTIListAll({
          attendanceSallaryTemplateId: this.attendanceSallaryTemplateId,
          configurationName: this.name
        });
        const arr = [];
        data.forEach((e, i) => {
          arr.push({
            configurationStatus: e.configurationStatus,
            configurationExplain: e.configurationExplain,
            sallaryImpact: String(e.sallaryImpact),
            id: e.id
          });
        });
        this.$nextTick(() => {
          this.form.setFieldsValue({
            keys: arr,
            configurationName: data[0].configurationName
          });
          setTimeout(() => {
            let num = 0;
            arr.forEach((e, i) => {
              this.form.setFieldsValue({
                [`configurationStatus${i}`]: e.configurationStatus,
                [`configurationExplain${i}`]: e.configurationExplain,
                [`sallaryImpact${i}`]: String(e.sallaryImpact)
              });
              if (this.id === e.id) {
                num = i;
              }
            });
            const dom = document.querySelectorAll(".status");
            const domOffsetTop = Array.from(dom).map(e => e.offsetTop);
            document.querySelector(".ant-drawer-wrapper-body").scrollTop = domOffsetTop[num];
          });
        });
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onAdd() {
      this.form.validateFields((err, values) => {
        if (!err) {
          values.keys.forEach((e, i) => {
            if (this.id) {
              // e.isSystemConfigure = false;
            } else {
              delete e.id;
            }
            e.attendanceSallaryTemplateId = this.attendanceSallaryTemplateId;
            e.configurationName = values.configurationName;
            e.configurationStatus = values[`configurationStatus${i}`];
            e.configurationExplain = values[`configurationExplain${i}`];
            e.sallaryImpact = parseFloat(values[`sallaryImpact${i}`]);
            e.sort = i + 1;
          });
          if (this.id) {
            this.onPutBatchUpdate(values.keys);
          } else {
            this.onPostBatchSave(values.keys);
          }
        }
      });
    },
    async onPostBatchSave(v) {
      try {
        await postBatchSave({
          attendanceSallaryTemplateItemAddDTOList: v
        });
        this.$emit("upDate", true);
        this.$emit("update:visible", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    async onPutBatchUpdate(v) {
      try {
        await putBatchUpdate({
          id: this.id,
          deleteIds: this.deleteIds,
          attendanceSallaryTemplateItemUpdateDTOArrayList: v
        });
        this.$emit("upDate", true);
        this.$emit("update:visible", false);
      } catch (err) {
        console.log("error log --> ", err);
      }
    },
    onClose() {
      // window.location.href = "/back/#/check/checkCard/imports";
      this.form.resetFields();
      setTimeout(() => {
        this.form.getFieldDecorator("keys", {
          initialValue: [{ configurationStatus: "", configurationExplain: "", sallaryImpact: "", id: null }],
          preserve: true
        });
      });
      this.$emit("upDate", false);
      this.$emit("update:visible", false);
    },
    remove(k) {
      const { form } = this;
      const keys = form.getFieldValue("keys");
      if (keys.length === 1) {
        return;
      }
      this.deleteIds.push(k.id);
      setTimeout(() => {
        form.setFieldsValue({
          keys: keys.filter(key => key !== k)
        });
      });
    },
    add() {
      const { form } = this;
      const keys = form.getFieldValue("keys");
      const nextKeys = keys.concat([{ configurationStatus: "", configurationExplain: "", sallaryImpact: "", id: null }]);
      form.setFieldsValue({
        keys: nextKeys
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.status {
  margin: 28px 0 18px 0;
  padding: 0 33px;
  .tit {
    font-size: 16px;
    font-weight: 500;
    color: #3c3d43;
  }
}
</style>
